import json,openpyxl,uuid,hashlib,requests
from django.conf import settings
from rest_framework_jwt.utils import jwt_decode_handler
import django.utils.timezone as timezone
from aaa import models
import re
class FileHandler(object):
    def __init__(self):
        self.filename = '/tmp/data.txt'
        self.dbname = '/tmp/dbname.txt'

    # messages的dump
    def dump(self,arr,db):
        f = open(self.filename, 'w',encoding='utf-8')
        f.write(json.dumps(arr))
        f.close()
        f2 = open(self.dbname, 'w')
        # db = re.search('\d+',db).group()
        f2.write(db)
        f2.close()

    # def dump(self,arr):
    #     print('arr',arr)
    #     f = open(self.filename, 'w',encoding='utf-8')
    #     f.write(json.dumps(arr))
    #     f.close()

    # messages的load
    def load(self):
        f = open(self.filename,'r',encoding='utf-8')
        arr = json.loads(f.read())
        print('arr',list(arr[0].values()))
        f2 = open(self.dbname,'r')
        db_number = f2.read()
        path = ('D:/work/export/%s.xlsx' % (list(arr[0].values())[0]))
        title = list(arr[0].keys())
        write_excel_with_title(arr, path, title)

    # def load(self):
    #     f = open(self.filename,'r',encoding='utf-8')
    #     arr = json.loads(f.read())
    #     print('load arr',arr)
    #     # f2 = open(self.dbname,'r')
    #     # db_number = f2.read()
    #     path = ('D:/桌面/yy1170.xlsx')
    #     title = list(arr[0].keys())
    #     write_excel_with_title(arr, path, title)

def write_excel_with_title(data: list, path: str, title):
    """把数据库写入到Excel"""
    # 实例化一个workbook
    workbook = openpyxl.Workbook()
    # 激活一个sheet
    sheet = workbook.active
    # 为sheet命名
    sheet.title = 'phone'
    # 准备keys
    keys = data[0].keys()
    # 准备写入数据
    for index, item in enumerate(data):
        # 遍历每一个元素
        for k, v in enumerate(keys):
            print(k, v)
            sheet.cell(row=index + 1, column=k + 1, value=str(item[v]))
    sheet.insert_rows(1)
    for i, v in enumerate(title):
        sheet.cell(1, i + 1, v)
    # 写入到文件
    workbook.save(path)

def get_random_str():
    m = hashlib.md5()
    m.update(str(uuid.uuid4()).encode('utf-8'))
    return m.hexdigest()

'''
获取openid
'''
def get_openid_by_code(code):
    print('get_openid_by_code',settings.WEIXIN_APPID, settings.WEIXIN_SECRET, code)
    url = 'https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code'
    get_url = url.format(settings.WEIXIN_APPID, settings.WEIXIN_SECRET, code)
    r = requests.get(get_url)
    return r.json()

# 通过token获取user_id
def get_api_user_id(request):
    try:
        token = request.META.get('HTTP_AUTHORIZATION')[5:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']

    except:
        user_id = None
    return user_id

def get_status_text(status):
    if status == 0:
        status_text = '订单提交'
    elif status == 1:
        status_text = '用户确认'
    elif status == 2:
        status_text = '已支付'
    elif status == 3:
        status_text = '已发货'
    elif status == 6:
        status_text = '交易成功'
    elif status == 7:
        status_text = '评价完成'
    elif status == 8:
        status_text = '申请退款'
    elif status == 9:
        status_text = '退款完成'
    elif status == 10:
        status_text = '交易关闭'
    else:
        status_text = '未识别状态'
    return status_text

def pay_complet_method(orderObj):
    orderObj.status = 2
    orderObj.is_pay = True
    orderObj.pay_date = timezone.datetime.now()
    orderObj.save()

def change_goods_num_sale(orderObj):
    ordergoods = models.GoodsOrderGoods.objects.filter(order=orderObj)
    for goods_item in ordergoods:
        try:
            productObj = models.GoodsProduct.objects.get(goods=goods_item.goods,
                                                  specifications=goods_item.specifications)
            productObj.number = productObj.number + goods_item.amount
            goodsObj = productObj.goods
            goodsObj.sale_num = goodsObj.sale_num - goods_item.amount
            goodsObj.save()
            productObj.save()
        except:
            pass
